package tools;

import java.util.HashMap;

/**
 * Created by yangxianming on 2018/1/4.
 * 不支持嵌套替换
   不包含${和}就跳出
 */
public class Replace {
    public String onlyDollar(String needReplace, HashMap<String, String> relation){

        if (!needReplace.contains("${"))
            return needReplace;
        if (!needReplace.substring(needReplace.indexOf("${")+2).contains("}"))
            return needReplace;

        int fromIndex = 0;
        while (true){
            int beginIndex = needReplace.indexOf("${", fromIndex) + 2;
            int endIndex = needReplace.indexOf("}", fromIndex + beginIndex);
            String tarString = needReplace.substring(beginIndex, endIndex);

            //从relation中找到需要替换的 如果没有找到就不做任何变化
            if (relation.containsKey(tarString)){
                String tarStringMark = "${" + tarString + "}";
                needReplace = needReplace.replace(tarStringMark, relation.get(tarString));
            }

            fromIndex = endIndex;
            //判断endIndex后是否还包含${,没有就break
            if (!needReplace.substring(fromIndex).contains("${"))
                break;
        }

        return needReplace;
    }
}
